import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import TabNav from './TabNav';
import TabContent from './TabContent';
import {immutableRenderDecorator} from 'react-immutable-render-mixin';
import CSSModules from 'react-css-modules';
import styles from './tab.module.scss';
import {Seq} from 'immutable';

@immutableRenderDecorator
@CSSModules(styles, {allowMultiple: true})

class Tabs extends Component {
  static propTypes = {
    children: PropTypes.oneOfType([
      PropTypes.arrayOf(PropTypes.node),
      PropTypes.node
    ]),
    defaultActiveIndex: PropTypes.number,
    activeIndex: PropTypes.number,
    onChange: PropTypes.func
  };

  static defaultProps = {
    onChange: () => {}
  };

  constructor (props) {
    super(props);

    const curProps = this.props;

    this.handleTabClick = this.handleTabClick.bind(this);
    this.immChildren = Seq(curProps.children);

    let activeIndex;
    if ('activeIndex' in curProps) {
      activeIndex = curProps.activeIndex;
    } else if ('defaultActiveIndex' in curProps) {
      activeIndex = curProps.defaultActiveIndex;
    }

    this.state = {
      activeIndex,
      prevIndex: activeIndex
    };
  }

  componentWillReceiveProps (nextProps) {
    if ('activeIndex' in nextProps) {
      this.setState({
        activeIndex: nextProps.activeIndex
      });
    }
  }

  handleTabClick (activeIndex) {
    const prevIndex = this.state.activeIndex;

    if (prevIndex !== activeIndex && 'defaultActiveIndex' in this.props) {
      this.setState({
        activeIndex,
        prevIndex
      });

      this.props.onChange({activeIndex, prevIndex});
    }
  }

  renderTabNav () {
    return (
      <TabNav
        onTabClick={this.handleTabClick}
        panels={this.immChildren}
        activeIndex={this.state.activeIndex}
      ></TabNav>
    );
  }

  renderTabContent () {
    return (
      <TabContent
        key="tabcontent"
        activeIndex={this.state.activeIndex}
        panels={this.immChildren}
      ></TabContent>
    )
  }

  render () {
    const {className} = this.props;
    const cx = classNames(className, 'ui-tabs');

    return (
      <div className={cx}>
        {
          this.renderTabNav()
        }
        {
          this.renderTabContent()
        }
      </div>
    )
  }
}

export default Tabs;